#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h> 
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "../include/gps.h"
#include "../include/port.h"
#define GPS_LEN 1024

/*int gps_analyse(char *buff,GPRMC *gps_data)
{
    char *ptr = NULL;
    if(NULL == gps_data)
    {
        return -1;
    }
    if(strlen(buff) < 10)
    {
        return -1;
    }
    if(NULL == (ptr = strstr(buff,"$GPRMC")))
    {
        return -1;
    }
    sscanf(ptr,"$GPRMC,%d.000,%c,%f,N,%f,E,%f,%f,%d,,,%c*",&(gps_data->time),&(gps_data->pos_state),&(gps_data->latitude),&(gps_data->longitude),&(gps_data->speed),&(gps_data->direction),&(gps_data->date),&(gps_data->mode));
    return 0;
}*/

void get_location(GPRMC *gps_data,char *buf)
{
    sprintf(buf,"经度：东经：%d度%d分%d秒,纬度：北纬：%d度%d分%d秒 当前速度：%.3fm/s",((int)gps_data->longitude) / 100, (int)(gps_data->longitude - ((int)gps_data->longitude / 100 * 100)), (int)(((gps_data->longitude - ((int)gps_data->longitude / 100 * 100)) - ((int)gps_data->longitude - ((int)gps_data->longitude / 100 * 100))) * 60.0),((int)gps_data->latitude) / 100, (int)(gps_data->latitude - ((int)gps_data->latitude / 100 * 100)), (int)(((gps_data->latitude - ((int)gps_data->latitude / 100 * 100)) - ((int)gps_data->latitude - ((int)gps_data->latitude / 100 * 100))) * 60.0),gps_data->speed);
}

char *get_GPS()
{
    int fd = 0;
    int fd1 = 0;
    int ret = 0;
    GPRMC gprmc;
    char buff[GPS_LEN] = {0};
    char *GPS = (char *)malloc(GPS_LEN);
    memset(GPS,0,GPS_LEN);
    char *devName = "/dev/ttyUSB2";
    fd = OpenUART(devName);
    ret = SetUART(fd,9600,0,8,1,'n');
    if (FALSE == ret)
    {
        printf("set UART error!\r\n");
        return NULL;
    }
    InitGPS(fd);
    char *devName1 = "/dev/ttyUSB1";
    fd1 = OpenUART(devName1);
    ret = SetUART(fd1,9600,0,8,1,'n');
    if (FALSE == ret)
    {
        printf("set UART error!\r\n");
        return NULL;
    }
    sleep(2);
    ret = read(fd1,buff,sizeof(buff));
    if (ret < 0)
    {
        perror("read error");
        return NULL;
    }
    memset(&gprmc,0,sizeof(gprmc));
    gps_analyse(buff,&gprmc);
    get_location(&gprmc,GPS);
    close(fd);
    close(fd1);
    return GPS;
}
